package com.sanjiahantang.youjiarole.module.me.scheme.views.impl;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.DensityUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.CircleImageView;
import com.sanjiahantang.uilibrary.views.MyListView;
import com.sanjiahantang.uilibrary.views.ObservableScrollView;
import com.sanjiahantang.uilibrary.views.supervideo.MediaController;
import com.sanjiahantang.uilibrary.views.supervideo.SuperVideoPlayer;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.cases.views.impl.DesignerDetailActivity;
import com.sanjiahantang.youjiarole.module.common.beans.UserOBean;
import com.sanjiahantang.youjiarole.module.common.views.impl.MyProjectpartnerActivity;
import com.sanjiahantang.youjiarole.module.me.scheme.beans.MeCaseOBean;
import com.sanjiahantang.youjiarole.module.me.scheme.presenters.MeSchemePresenter;
import com.sanjiahantang.youjiarole.module.me.scheme.views.MeSchemeView;
import com.sanjiahantang.youjiarole.utils.FileUtils;
import com.sanjiahantang.youjiarole.utils.SPUtils;
import com.squareup.picasso.Picasso;

import java.util.List;


/**
 * Created by zy on 2017/8/16.
 * 案例详情
 */

public class MeSchemeCaseDetailActivity extends BaseMvpActivity<MeSchemeView, MeSchemePresenter> implements MeSchemeView, View.OnClickListener, ObservableScrollView.OnScrollChangedListener {
    private MeSchemeCaseDetailActivity $this;
    private SuperVideoPlayer mSuperVideoPlayer;
    private View mPlayBtnView, inc, flVideo;
    private ObservableScrollView svMainContent;
    private TextView title, txtRoomType, txtDesignerName, meZX, choiceZX,txt3D;
    private ImageView ivHeader, ivGoOfTitle, ivFavoriteOfTitle, ivGo, ivFavorite;
    private MyListView lvInfo;
    private View rlDesigner, rlBack;
    private View containPanel, rlElse, flGo;
    private String videoUrl = null;
    private MeCaseOBean.InformationListBean caseDetail;
    private int isCollected = 0;
    int id_o;
    private ImageView iv_isCommitOrder;
    private CircleImageView ivDesignerPhoto;

    private String version,roamId = null;
    private int ucrId;
    private String currentRoleId;
    private String currentPhone;

    @Override
    public MeSchemePresenter initPresenter() {
        return new MeSchemePresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_me_case_detail);
        $this = this;
        mSuperVideoPlayer = (SuperVideoPlayer) findViewById(R.id.video_player_item_1);
        mPlayBtnView = findViewById(R.id.play_btn);
        currentRoleId = SPUtils.get($this,SPConfig.ROLE_ID,"").toString();
        currentPhone = SPUtils.get($this,SPConfig.PHONE,"").toString();

        inc = findViewById(R.id.inc);
        rlBack = findViewById(R.id.rlBack);
        flVideo = findViewById(R.id.mainTitle);
        svMainContent = (ObservableScrollView) findViewById(R.id.scroller);
        title = (TextView) findViewById(R.id.title);
        ivHeader = (ImageView) findViewById(R.id.ivHeader);
        containPanel = findViewById(R.id.contentPanel);
        rlElse = findViewById(R.id.rlElse);
        txtRoomType = (TextView) findViewById(R.id.txtRoomType);
        ivGoOfTitle = (ImageView) findViewById(R.id.icon1);
        ivFavoriteOfTitle = (ImageView) findViewById(R.id.icon2);
        ivFavoriteOfTitle.setOnClickListener(this);
        ivGo = (ImageView) findViewById(R.id.ivGo);
        ivFavorite = (ImageView) findViewById(R.id.ivFavorite);
        ivDesignerPhoto = (CircleImageView) findViewById(R.id.ivDesignerPhoto);
        findViewById(R.id.flGo).setOnClickListener(this);
        lvInfo = (MyListView) findViewById(R.id.lvInfo);
        id_o = getIntent().getIntExtra(KEY_ID, 0);
        iv_isCommitOrder = (ImageView) findViewById(R.id.isCommitOrder);
        txtDesignerName = (TextView) findViewById(R.id.txtDesignerName);
        meZX = (TextView) findViewById(R.id.meZX);
        choiceZX = (TextView) findViewById(R.id.choiceZX);
        txt3D = (TextView) findViewById(R.id.txt3D);
        findViewById(R.id.fl_Left).setOnClickListener(this);
        meZX.setOnClickListener(this);
        txt3D.setOnClickListener(this);
        choiceZX.setOnClickListener(this);
        findViewById(R.id.rlDesigner).setOnClickListener(this);
        findViewById(R.id.flFavorite).setOnClickListener(this);
        findViewById(R.id.flFavorite).setVisibility(View.GONE);
        findViewById(R.id.flGo).setVisibility(View.GONE);

//        if (isCommitOrder.equals("1")){
//            iv_isCommitOrder.setVisibility(View.VISIBLE);
//        }else {
//
//        }
        iv_isCommitOrder.setVisibility(View.GONE);

        if (id_o > 0) {
            presenter.setDetailCallBack(new DetailCallBack() {

                @Override
                public void loadData(MeCaseOBean.Data data) {
                    if (data != null && data.getInformationList() != null && data.getInformationList().size() > 0) {
                        //载入视频信息
                        final MeCaseOBean.InformationListBean detail = data.getInformationList().get(0);
                        ucrId = detail.getUserRequireId();
                        List<MeCaseOBean.PicList> picList = data.getPicList();
                        for (MeCaseOBean.PicList pic : picList) {
                            if (pic.getPicCaId() == 15) {
                                videoUrl = pic.getUrl();
                                break;
                            }
                        }
                        version = detail.getVersion();
                        //videoUrl = "http://vod.cdn1.v.17173.com/295400817b3f772a00166e10964c5a00cd10d5ab660055b4/ra6/FLVList/20100121/sexycorn_612777_1.mp4";


                        if (!TextUtils.isEmpty(videoUrl)) {
                            //          findViewById(R.id.play_btn2).setVisibility(View.VISIBLE);
                            //  findViewById(R.id.play_btn2).setOnClickListener(this);
                        }
                        txtRoomType.setText(detail.getLikeStyleName() + " , "
                                + detail.getApartmentTypeName() + " , "
                                + detail.getApartmentArea() + "㎡");
                        txtDesignerName.setText(detail.getDesignRoleName());
                        Picasso.with($this).load(FileUtils.rePath(detail.getUrl())).placeholder(R.drawable.i_match).into(ivDesignerPhoto);
                        if (videoUrl != null) {
                            //  String url = detail.getUrl();
                            //   if (detail.getUrl().indexOf("http") != 0) {
                            //        url = ConfigValue.IMG_IP + url;
                            //    }
                            Picasso.with($this).load(videoUrl)
                                    .placeholder(R.drawable.i_match)
                                    .error(R.drawable.i_match)
                                    .into(ivHeader);
                        } else {
                            ivHeader.setImageResource(R.drawable.i_match);
                        }
                        caseDetail = detail;
                        if (TextUtils.isEmpty(detail.getRoamId())){
                            txt3D.setVisibility(View.GONE);
                            roamId = null;
                        }else{
                            txt3D.setVisibility(View.VISIBLE);
                            roamId = detail.getRoamId();
                        }
                        //非官方
                        if (detail.getIsOfficial() == 0){

                            if (detail.getTotalStateId() > 0){

                                String phone = SPUtils.get($this, SPConfig.PHONE, "").toString();
                                int type = 0;//0只显示报价 1显示项目2 显示监理
                                if (TextUtils.isEmpty(detail.getProjectRoleId())){
                                    type = 1;
                                }else if(detail.getProjectStateId() > 0 && TextUtils.isEmpty(detail.getSupervisionId()) && phone.equals(detail.getProjectRoleId())){
                                    type = 2;
                                }

                                if (type == 1){
                                    if (currentPhone.equals(detail.getDesignRoleId())){
                                        meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimaryLight));
                                        choiceZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                                        choiceZX.setVisibility(View.VISIBLE);
                                        choiceZX.setText("选择项目经理");
                                        choiceZX.setTag(R.id.decode,1);
                                    }else{
                                        meZX.setVisibility(View.VISIBLE);
                                        meZX.setBackgroundResource(R.color.colorPrimary);
                                    }
                                }else if(type == 2){
                                    meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimaryLight));
                                    choiceZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                                    choiceZX.setVisibility(View.VISIBLE);
                                    choiceZX.setText("选择监理");
                                    choiceZX.setTag(R.id.decode,2);
                                }else {
                                    choiceZX.setVisibility(View.GONE);
                                    meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                                }
                            }else{
                                choiceZX.setVisibility(View.GONE);
                                meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                            }

                        }else{
                            //官方


                            if (detail.getTotalStateId() == 2 && TextUtils.isEmpty(detail.getProjectRoleId())
                                    ) {//显示项目经理

                                if (currentPhone.equals(detail.getDesignRoleId())){
                                    meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimaryLight));
                                    choiceZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                                    choiceZX.setVisibility(View.VISIBLE);
                                    choiceZX.setTag(R.id.decode,1);
                                }else {
                                    meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                                    meZX.setVisibility(View.VISIBLE);
                                    choiceZX.setVisibility(View.GONE);
                                }

                            } else if(currentPhone.equals(detail.getProjectRoleId()) && currentRoleId.contains("3") && detail.getTotalStateId() == 2 && detail.getProjectStateId() > 0 && detail.getEngnieeStatusId() <= 10 && detail.getIsSubcontractProject() == 0){
                                //工程分包
                                meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimaryLight));
                                choiceZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                                choiceZX.setVisibility(View.VISIBLE);
                                choiceZX.setTag(R.id.decode,3);
                                choiceZX.setText("分包");
                            } else {
                                choiceZX.setVisibility(View.GONE);
                                meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                            }


                        }


                        /////***** 项目经理设计阶段 在设计师推送报价前不显示报价按钮 推送后不可编辑清单

                        final String phone = SPUtils.get($this, SPConfig.PHONE, "").toString();
                        ConfigValue.param = null;
                        if (!(phone.equals(detail.getDesignRoleId()) || (detail.getIsSubcontract() == 1 && phone.equals(detail.getDesignPhone())))) {
                            if (detail.getPushStateId() == 0) {
                                meZX.setVisibility(View.GONE);
                                choiceZX.setVisibility(View.GONE);
                            } else {
                                meZX.setVisibility(View.VISIBLE);
                                ConfigValue.param = new Object();
                            }
                        } else {
                            meZX.setVisibility(View.VISIBLE);
                        }

                        if (detail.getTotalStateId() == 1){
                            presenter.checkcCustomerIsOrder($this, String.valueOf(id_o), version, new BaseView.OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {
                                    if (content != null && content instanceof String){
                                        String result = (String) content;
                                        if (result.contains("true")){
                                            meZX.setBackgroundResource(R.color.colorPrimary);
                                            meZX.setOnClickListener($this);
                                        }else{
                                            if (detail.getIsSubcontract() == 1 && phone.equals(detail.getDesignRoleId())){
                                                meZX.setBackgroundResource(R.color.gray_e8);
                                                meZX.setOnClickListener(null);
                                            }else{
                                                meZX.setBackgroundResource(R.color.colorPrimary);
                                                meZX.setOnClickListener($this);
                                            }
                                        }
                                    }
                                }
                            });
                        }

                    } else {
                        Utils.showToast($this, "没有找到方案");
                        finish();
                    }

                }

                @Override
                public void initAdapter(QuickAdapter adapter) {
                    lvInfo.setAdapter(adapter);
                }
            });
            presenter.loadCaseById($this, id_o);
            rlBack.setOnClickListener(this);
        } else {
            Utils.showToast($this, "很抱歉，案例找不到了~");
            finish();
        }

    }

    @Override
    public void initData() {

        mPlayBtnView.setOnClickListener(this);
        mSuperVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);
        inc.setVisibility(View.GONE);
        svMainContent.setOnScrollChangedListener(this);
        title.setText("案例详情");
    }

    @Override
    public void onBackPressed() {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            this.getResources().getConfiguration().orientation = Configuration.ORIENTATION_PORTRAIT;
            mVideoPlayCallback.onSwitchPageType();
            return;
        }
        super.onBackPressed();

    }

    @Override
    public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {

        if (Utils.checkIsVisible(this, rlBack)) {
            showTitleView(View.GONE);
        } else {
            showTitleView(View.VISIBLE);
            if (Utils.checkIsVisible(this, rlElse)) {
                ivGoOfTitle.setVisibility(View.GONE);
                ivFavoriteOfTitle.setVisibility(View.GONE);
            } else {
//                ivGoOfTitle.setVisibility(View.VISIBLE);
//                ivFavoriteOfTitle.setVisibility(View.VISIBLE);
            }

        }
    }

    private void showTitleView(int state) {
        inc.setVisibility(state);
//        ivGoOfTitle.setVisibility(state);
//        ivFavoriteOfTitle.setVisibility(state);
    }


    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    /**
     * 播放器的回调函数
     */
    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        /**
         * 播放器关闭按钮回调
         */
        @Override
        public void onCloseVideo() {
            mSuperVideoPlayer.close();//关闭VideoView
            mPlayBtnView.setVisibility(View.VISIBLE);
            mSuperVideoPlayer.setVisibility(View.GONE);
            resetPageToPortrait();
        }

        /**
         * 播放器横竖屏切换回调
         */
        @Override
        public void onSwitchPageType() {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
                containPanel.setVisibility(View.VISIBLE);
                rlElse.setVisibility(View.VISIBLE);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                mSuperVideoPlayer.setPageType(MediaController.PageType.EXPAND);
                containPanel.setVisibility(View.GONE);
                rlElse.setVisibility(View.GONE);


            }
        }

        /**
         * 播放完成回调
         */
        @Override
        public void onPlayFinish() {

        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.rlBack:
                finish();
                break;
            case R.id.fl_Left:
                finish();
                break;
            case R.id.flFavorite:
            case R.id.icon2://收藏
                if (isCollected == 1) {
                    isCollected = 0;
                    ivFavorite.setImageResource(com.sanjiahantang.uilibrary.R.drawable.i_heart_white);
                    ivFavoriteOfTitle.setImageResource(com.sanjiahantang.uilibrary.R.drawable.i_heart_black);
                } else {
                    isCollected = 1;
                    ivFavorite.setImageResource(com.sanjiahantang.uilibrary.R.drawable.i_heart_red_on);
                    ivFavoriteOfTitle.setImageResource(com.sanjiahantang.uilibrary.R.drawable.i_heart_red_on);
                }

                presenter.addCollectInfo(this, id_o);
                break;
            case R.id.rlDesigner:
                if (caseDetail != null) {
                    startActivity(new Intent($this, DesignerDetailActivity.class)
                            .putExtra(KEY_PHONE, caseDetail.getDesignRoleId())
                            .putExtra(KEY_ID, caseDetail.getId())
                    );
                }
                break;
            default:
                if (videoUrl == null) {
                    Utils.showToast($this, "无法加载该视频");
                    return;
                }
                mPlayBtnView.setVisibility(View.GONE);
                mSuperVideoPlayer.setVisibility(View.VISIBLE);
                mSuperVideoPlayer.setAutoHideController(false);
                Uri uri = Uri.parse(videoUrl);
                mSuperVideoPlayer.loadAndPlay(uri, 0);
                break;
            case R.id.meZX://报价清单详情
                presenter.checkcCustomerIsOrder(this, String.valueOf(id_o), version);
                break;
            case R.id.choiceZX:
                Object tag = choiceZX.getTag(R.id.decode);
                if (tag != null && tag instanceof Integer){
                    int type = (int) tag;
                    if (type == 1){
                        //项目经理
                        Intent intent = new Intent($this, MyProjectpartnerActivity.class);
                        intent.putExtra(KEY_TYPE, 2);
                        startActivityForResult(intent, 1);
                    }else if(type == 2){
                        //监理
                        Intent intent = new Intent($this, MyProjectpartnerActivity.class);
                        intent.putExtra(KEY_TYPE, 3);
                        startActivityForResult(intent, 2);
                    }else if(type == 3){
                        //工程分包
                        Intent intent = new Intent($this, MyProjectpartnerActivity.class);
                        intent.putExtra(KEY_TYPE, 5);
                        startActivityForResult(intent, 3);
                    }else{
                        Utils.showToast($this,"不应该出现");
                    }
                }else{
                    Utils.showToast($this,"不应该出现");
                }

                break;
            case R.id.flGo:
                Utils.showToast($this, "分享成功");
                break;
            case R.id.txt3D:
                if(TextUtils.isEmpty(roamId)){
                    Utils.showToast($this,"没有3D漫游方案");
                }else{
                    Utils.showToast($this,"等待接入3D漫游方案");
                }
                break;


        }

    }

    /***
     * 旋转屏幕之后回调
     *
     * @param newConfig newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (null == mSuperVideoPlayer) return;
        /***
         * 根据屏幕方向重新设置播放器的大小
         */
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().getDecorView().invalidate();
            float height = DensityUtils.getWidthInPx(this);
            float width = DensityUtils.getHeightInPx(this);
            mSuperVideoPlayer.getLayoutParams().height = (int) width;
            mSuperVideoPlayer.getLayoutParams().width = (int) height;
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
//            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            float width = DensityUtils.getWidthInPx(this);
            float height = DensityUtils.dp2px(this, 200.f);
            mSuperVideoPlayer.getLayoutParams().height = (int) height;
            mSuperVideoPlayer.getLayoutParams().width = (int) width;
        }
    }

    /***
     * 恢复屏幕至竖屏
     */
    private void resetPageToPortrait() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.loadCaseById($this, id_o);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    UserOBean.Data item = (UserOBean.Data) data.getSerializableExtra(KEY_PARAM);
                    presenter.UpdateProjectDesign($this, "0",item, ucrId, id_o);
                    choiceZX.setVisibility(View.GONE);
                    meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    break;
                case 2:
                    UserOBean.Data item2 = (UserOBean.Data) data.getSerializableExtra(KEY_PARAM);
                    presenter.UpdateProjectDesign($this, "2",item2, ucrId, id_o);
                    choiceZX.setVisibility(View.GONE);
                    meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    break;
                case 3:
                    UserOBean.Data item3 = (UserOBean.Data) data.getSerializableExtra(KEY_PARAM);
                    presenter.addRequireSubcontractInfoByProject($this, item3, ucrId, new BaseView.OnLoadListener() {
                        @Override
                        public void onLoad(Object content) {
                            choiceZX.setVisibility(View.GONE);
                            meZX.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                        }
                    });

                    break;
            }
        }
    }
}

